//
//  NSObject+HDPrvinceCityDataManager.m
//  app
//
//  Created by D on 15/5/11.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDPrvinceCityDataManager.h"


@interface HDPrvinceCityDataManager ()

@property (nonatomic, retain) JKHttpClient * http;
@property (nonatomic, retain) JKHttpClient * httpTest;
@property (nonatomic, strong) SNUniteUrl * uniteUrl;
@property (nonatomic, retain) NSMutableArray * mutableArray;
@property (nonatomic,retain) FMDatabaseQueue * fmdbQueue;

@property (nonatomic, retain) NSData * myData;
@property (nonatomic, assign) BOOL includeProvince;
@property (nonatomic, assign) BOOL includeData;

@end

@implementation HDPrvinceCityDataManager

+ (HDPrvinceCityDataManager *)shareManager
{
    AS_SINGLETON(HDPrvinceCityDataManager, manager, {
        manager = [[HDPrvinceCityDataManager alloc] init];
        manager.http = [[JKHttpClient alloc] init];
        manager.httpTest = [[JKHttpClient alloc] init];
        manager.uniteUrl = [SNUniteUrl shareUniteUrl];
        manager.mutableArray = [[NSMutableArray alloc] init];
        HDAppDelegate * delegate = (HDAppDelegate *)[UIApplication sharedApplication].delegate;
        manager.fmdbQueue = delegate.fmdbQueue;
    })
    return manager;
}

- (void)loadPrvinceCityData:(HDPrvinceCityHttpResult *)result
{
    if ([self.http isRunning]) {
        return;
    }
    
    /** 修改地址获取地址连接 -modified by khzliu */
    //NSString * provineceUrl = [NSString stringWithFormat:@"%@9",self.uniteUrl.static_city_carrypageUrl];
    NSString * provineceUrl = self.uniteUrl.static_city_carrypageUrl;
    
    [self.httpTest get:provineceUrl result:^(JKResponse *resp) {
       
        if (resp.OK) {
            result.success = YES;
            
            result.dataArray = [self provinceDataSourceArrayWithArray:resp.content[@"result"]];
        }else if (resp.failure){
            result.failure = YES;
        }
        [result invoke];
    }];
    
}

#pragma mark - 网络返回数据的处理
- (NSArray *)provinceDataSourceArrayWithArray:(NSArray *)array
{
    //将刷新的时间保存起来
    NSDate * date = [NSDate date];
    NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
    [ud setObject:date forKey:@"provinceLastRefreshTime"];
    
    [self.mutableArray removeAllObjects];
    [self saveDataToDB:array];
    
//    for (NSDictionary * dict in array) {
        [self.mutableArray addObject:[HDProvinceModel modelWithDict:array]];
//    }
    
    return self.mutableArray;
}

#pragma mark - 保存数据到数据库
- (void)saveDataToDB:(NSArray *)array
{
    //删除以前的数据表
//    [self deleteSpecial];
    
    [self createFmdb];
    
    NSData * data = [NSKeyedArchiver archivedDataWithRootObject:array];
    
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        if ([db executeUpdate: @"insert into Province (Data) values (?);",data]) {
            DLog(@"已经将Province第一页的数据添加到了数据库");
        }
//        [db close];
    }];
//    [self.fmdbQueue close];
}

#pragma mark - 是否自动刷新数据
- (BOOL)shouldRefreshProvinceData
{
    NSFileManager * fm = [NSFileManager defaultManager];
    
    if ([fm fileExistsAtPath:kDBPath]) {//数据库文件已经存在
        //判断表是不是存在:
        if ([self fmdbIncludeProvince]) {//表是存在的
            //通过时间判断是否需要自动刷新
            NSUserDefaults * ud = [NSUserDefaults standardUserDefaults];
            NSDate * provinceLastRefreshTime = [ud objectForKey:@"provinceLastRefreshTime"];
            NSDate * nowDate = [NSDate date];
            DLog(@"provinceLastRefreshTime ==== %@",provinceLastRefreshTime);
            NSTimeInterval aTimer = [nowDate timeIntervalSinceDate:provinceLastRefreshTime];
            DLog(@"Province时间差  ===== %f",aTimer);
            if (aTimer > PROVINCEREFRESHSETIME) {//已经有一段时间没有刷新了,需要自动刷新
                DLog(@"Province需要自动刷新");
                return YES;
            } else {//不需要自动刷新
                DLog(@"Province不需要自动刷新");
                return NO;
            }
        } else {//表不存在,第一次进入此页面
            return YES;
        }
    } else {//数据库文件都不存在,第一次进入这个页面
        return YES;
    }
}

#pragma mark - 创建表
- (void)createFmdb
{
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        NSString * sql = @"create table if not exists Province(ID integer primary key autoincrement, Data blob);";
        BOOL ret2 = [db executeUpdate:sql];
        if (ret2) {
            DLog(@"创建Province表成功");
        }
//        [db close];
    }];
//    [self.fmdbQueue close];
}

#pragma mark - 从数据库中读取数据
- (NSArray *)arrayFromFmdb
{
    self.myData = [NSData data];
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        if ([[db executeQuery:@"select * from sqlite_master where name  = 'Province';"] next]){
            NSString * sql = @"select * from Province;";
            FMResultSet * set = [db executeQuery:sql];
            
            if ([set next]) {
                self.myData = [set dataForColumn:@"Data"];
            }
            
        }
//        [db close];
    }];
//    [self.fmdbQueue close];
    
    NSArray * array = [NSKeyedUnarchiver unarchiveObjectWithData:self.myData];
    [self.mutableArray removeAllObjects];
//    for (NSDictionary * dict in array) {
        [self.mutableArray addObject:[HDProvinceModel modelWithDict:array]];
//    }
    return self.mutableArray;
}

#pragma mark - 表是否存在
- (BOOL)fmdbIncludeProvince
{
    NSFileManager * fm = [NSFileManager defaultManager];
    if ([fm fileExistsAtPath:kDBPath]) {//数据库文件已经存在
        //判断表是不是存在:
        [self.fmdbQueue inDatabase:^(FMDatabase *db) {
            if ([[db executeQuery:@"select * from sqlite_master where name  = 'Province';"] next]) {//表是存在的
                DLog(@"Province表存在");
                self.includeProvince = YES;
            } else {//表不存在,第一次进入此页面
                DLog(@"Province表不存在");
                self.includeProvince = NO;
            }
//            [db close];
        }];
//        [self.fmdbQueue close];
    } else {//数据库文件都不存在,第一次进入这个页面
        self.includeProvince = NO;
    }
    return self.includeProvince;
}

#pragma mark - 表中是否存有数据
- (BOOL)fmdbIncludeData
{
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        if ([[db executeQuery:@"select * from sqlite_master where name  = 'Province';"] next]){
            
            FMResultSet * set = [db executeQuery:@"select * from Province;"];
            
            if ([set next]) {
                DLog(@"Province表格中数据是存在的");
                self.includeData =  YES;
            } else {
                DLog(@"Province表格中数据不存在");
                self.includeData =  NO;
            }
            
        } else {
            self.includeData =  NO;
        }
//        [db close];
    }];
//    [self.fmdbQueue close];
    return self.includeData;
}

#pragma mark - 删除表
-(void)deleteProvince
{
    [self.fmdbQueue inDatabase:^(FMDatabase *db) {
        if ([[db executeQuery:@"select * from sqlite_master where name  = 'Province';"] next]) {//表是存在的
//            [db close];
//            [db open];
            if ([db executeUpdate:@"drop table Province;"]) {
                DLog(@"Province表格已经删除");
            }
        }
//        [db close];
    }];
//    [self.fmdbQueue close];
}


#pragma mark - 判断是否刷新
-(BOOL)shouldRfreshProvinceData
{
    if (![[[NSUserDefaults standardUserDefaults]objectForKey:@"provinceUrl"] isEqualToString:self.uniteUrl.static_city_carrypageUrl]) {
        
        [[NSUserDefaults standardUserDefaults] setObject:self.uniteUrl.static_city_carrypageUrl forKey:@"provinceUrl"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        return YES;
    }else
        return NO;
}
@end







